package com.tarena.lbs.content.dao.repository.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.tarena.lbs.content.dao.mapper.CategoryMapper;
import com.tarena.lbs.content.dao.repository.CategoryRepository;
import com.tarena.lbs.content.pojo.po.ArticleCategoryPO;
import com.tarena.lbs.content.pojo.query.ArticleCategoryQuery;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import java.util.List;

@Repository
@Slf4j
public class CategoryRepositoryImpl implements CategoryRepository {
    @Autowired
    private CategoryMapper categoryMapper;

    @Override
    public PageInfo<ArticleCategoryPO> pageList(ArticleCategoryQuery query) {
        // 开启分页
        PageHelper.startPage(query.getPageNo(), query.getPageSize());

        QueryWrapper<ArticleCategoryPO> queryWrapper = new QueryWrapper<>();
        if(query.getCategoryName() != null && !query.getCategoryName().trim().isEmpty()){
            queryWrapper.like("category_name", query.getCategoryName());
        }
        
        // 添加分类状态查询条件
        if (query.getCategoryStatus() != null) {
            queryWrapper.eq("category_status", query.getCategoryStatus());
        }

        // 添加排序
        queryWrapper.orderByAsc("sort");

        List<ArticleCategoryPO> list = categoryMapper.selectList(queryWrapper);
        return new PageInfo<>(list);
    }

    @Override
    public void save(ArticleCategoryPO po) {
        if (po.getId() != null) {
            categoryMapper.updateById(po);
        } else {
            categoryMapper.insert(po);
        }
    }
    @Override
    public boolean existsByCategoryName(String categoryName) {
        QueryWrapper<ArticleCategoryPO> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("category_name", categoryName);
        return categoryMapper.selectCount(queryWrapper) > 0;
    }

    @Override
    public ArticleCategoryPO getById(Integer id) {
        return categoryMapper.selectById(id);
    }

    @Override
    public int deleteById(Integer id) {
        return categoryMapper.deleteById(id);
    }

    @Override
    public List<ArticleCategoryPO> getAllEnabledCategories() {
        return categoryMapper.selectAllEnabledCategories();
    }
}